package com.kx.center.controller;

import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kx.center.auth.Authentication;
import com.kx.center.entity.Account;
import com.kx.center.entity.StoreAppAccount;
import com.kx.center.entity.StoreInfo;
import com.kx.center.entity.common.Region;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.exception.AccountAlreadyExistsException;
import com.kx.center.service.RegionService;
import com.kx.center.service.StoreAppAccountService;
import com.kx.center.service.StoreManagerService;
import com.kx.center.util.JSONParser;
import com.kx.center.util.Response;

/**
 * Created by acmen on 16-1-4.
 * 门店管理
 * 1. 门店信息管理
 * 2. 门店APP 管理
 * 3. 门店多渠道管理
 */
@Controller
@RequestMapping("/shop")
public class ShopController extends CommonController{

    @Autowired
    private RegionService regionService;

    @Autowired
    private StoreManagerService storeManagerService;

    @Autowired
    private StoreAppAccountService storeAppAccountService;
    

	@Autowired
	StoreAppAccountService accountService;
	

    /**
     * 获取省份信息
     * @param request
     * @return
     */
    @RequestMapping(value = "province_list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Authentication
    public String getProvinceList(HttpServletRequest request){

        List<Region> provinceList = regionService.findProvince();
        if(provinceList == null || provinceList.size() <= 0){
            return Response.error(MessageCode.NO_DATA, "没有省份数据");
        }
        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("data", provinceList);
        return Response.success(result);
    }

    /**
     * 获取省份下的城市信息
     * @param request
     * @return
     */
    @RequestMapping(value = "city_list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Authentication
    public String getCityList(HttpServletRequest request){

        int provinceId = 0;
        try{
            provinceId = Integer.valueOf(request.getParameter("province_id"));
        }catch (Exception e){
            return Response.error(MessageCode.REQUEST_ERROR, "无效的省份信息");
        }

        if(provinceId <= 0){
            return Response.error(MessageCode.REQUEST_ERROR, "无效的省份信息");
        }

        List<Region> cityList = regionService.findCity(provinceId);
        if(cityList == null || cityList.size() <= 0){
            return Response.error(MessageCode.NO_DATA, "没有城市数据");
        }
        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("data", cityList);
        return Response.success(result);
    }

    @RequestMapping(value = "area_list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Authentication
    public String getAreaList(HttpServletRequest request){

        int cityId = 0;
        try{
            cityId = Integer.valueOf(request.getParameter("city_id"));
        }catch (Exception e){
            return Response.error(MessageCode.REQUEST_ERROR, "无效的城市信息");
        }

        if(cityId <= 0){
            return Response.error(MessageCode.REQUEST_ERROR, "无效的城市信息");
        }

        List<Region> areaList = regionService.findArea(cityId);
        if(areaList == null || areaList.size() <= 0){
            return Response.error(MessageCode.NO_DATA, "没有区域数据");
        }
        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("data", areaList);
        return Response.success(result);
    }


    /**
     * 添加门店
     * 1. 校验参数
     * 2. 检查门店名称是否重复
     * 3. 添加门店
     * @param request
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Authentication
    public String addStore(HttpServletRequest request){

        Account userAccount = this.getCommonUserAccount(request);
        if(userAccount == null){
            return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
        }

        int companyId = userAccount.getCompanyId();

        String[] storeInfoParas = {"store_name","store_type","shipping_date","shipping_start_time","shipping_end_time","latitude","longitude","range","province","city","area","address","shop_owner","mobile","show_img1","show_img2","store_desc","freight_type","freight_fee","starting_price","freight_limit","is_bookable","invoice","invoice_min_amount","invoice_description","push_type","payment_type"};
        Map<String,String> paraMap = this.listRequsetParamaters(request, storeInfoParas);


        StoreInfo storeInfo = new StoreInfo();
        boolean storeInfoStatus = storeInfo.initStoreBean(paraMap);
        if(!storeInfoStatus){
            return Response.error(MessageCode.NO_DATA, "数据校验错误");
        }

        try{
            int provinceId = Integer.valueOf(storeInfo.getProvince());
            Region regionInfo = regionService.getRegionById(provinceId);
            if(regionInfo != null){
                if(regionInfo.getRegionType() != 1){
                    return Response.error(MessageCode.NO_DATA, "数据校验错误");
                }else{
                    storeInfo.setProvince(regionInfo.getRegionName());
                }
            }else{
                return Response.error(MessageCode.NO_DATA, "数据校验错误");
            }

            int cityId = Integer.valueOf(storeInfo.getCity());
            regionInfo = regionService.getRegionById(cityId);
            if(regionInfo != null){
                if(regionInfo.getRegionType() != 2 || regionInfo.getParentId() != provinceId){
                    return Response.error(MessageCode.NO_DATA, "数据校验错误");
                }else{
                    storeInfo.setCity(regionInfo.getRegionName());
                }
            }else{
                return Response.error(MessageCode.NO_DATA, "数据校验错误");
            }

            int areaId = Integer.valueOf(storeInfo.getArea());
            regionInfo = regionService.getRegionById(areaId);
            if(regionInfo != null){
                if(regionInfo.getRegionType() != 3 || regionInfo.getParentId() != cityId){
                    return Response.error(MessageCode.NO_DATA, "数据校验错误");
                }else{
                    storeInfo.setArea(regionInfo.getRegionName());
                }
            }else{
                return Response.error(MessageCode.NO_DATA, "数据校验错误");
            }

        }catch (Exception e){
            return Response.error(MessageCode.NO_DATA, "数据校验错误");
        }

        storeInfo.setStatus(1);
        storeInfo.setOperatorId(userAccount.getId());
        storeInfo.setCompanyId(companyId);

        StoreInfo storeInfoResult = storeManagerService.findStoreInfoByStoreName(companyId , storeInfo.getStoreName());
        if(storeInfoResult != null){
            return Response.error(MessageCode.NO_DATA, "门店名称已存在");
        }

        int addStoreInfo = storeManagerService.addStoreInfo(storeInfo);
        if(addStoreInfo <= 0){
            return Response.error(MessageCode.OPERATOR_FAIL, "添加账户失败");
        }

        return Response.success();

    }

    @RequestMapping(value = "list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Authentication
    public String listStore(HttpServletRequest request){

        String pageNumStr = org.apache.commons.lang3.StringUtils.trimToEmpty(request.getParameter("page_num"));
        String pageSizeStr = org.apache.commons.lang3.StringUtils.trimToEmpty(request.getParameter("page_size"));

        Account account = this.getCommonUserAccount(request);
        int companyId = account.getCompanyId();
        		
        
        int pageNum = 0;
        int paseCount = 10;

        try{
            pageNum = Integer.valueOf(pageNumStr);
            paseCount = Integer.valueOf(pageSizeStr);
        }catch(Exception e){

        }

        Map<String,Object> where = new HashMap<String, Object>();
        where.put("company_id", companyId);
        List<StoreInfo> storeList = storeManagerService.getStoreInfoList(pageNum, paseCount, where);

        int hasNextPage = 0;
        if(storeList.size() == (paseCount+1)){
            storeList.remove(paseCount);
            hasNextPage = 1;
        }

        HashMap<String,Object> result = new HashMap<String,Object>();
        result.put("has_more", hasNextPage);
        result.put("store_list", storeList);
        result.put("current_page", pageNum);

        return Response.success(result);

    }

    @RequestMapping(value = "edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Authentication
    @SuppressWarnings("unchecked")
    public String editStore(HttpServletRequest request) throws Exception{

        Account userAccount = this.getCommonUserAccount(request);
        if(userAccount == null){
            return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
        }

    	String json = request.getParameter("json");
        
		if (StringUtils.isBlank(json)) {
			return Response.error(MessageCode.JSON_WRONG);
		}

		HashMap<String, Object> data = new HashMap<String, Object>();
		try {
			data = (HashMap<String, Object>) JSONParser.parse(json,
					new HashMap<String, Object>().getClass());
		} catch (Exception e) {
			e.printStackTrace();
			return Response.error(MessageCode.JSON_WRONG);
		}
		
        Iterator<Entry<String, Object>> itera = data.entrySet().iterator();  
        while(itera.hasNext()){  
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>)itera.next();  
            if(entry.getValue() == null || entry.getValue().equals("")){ 
            	return Response.error(MessageCode.PARAMETER_WRONG);  
            }  
        }  
          
		storeManagerService.updateStoreInfoById(userAccount, data);
		
        return Response.success("门店信息修改成功!");

    }
    
    @RequestMapping(value = "delete", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Authentication
    public String deleteStore(HttpServletRequest request) throws Exception{

        Account userAccount = this.getCommonUserAccount(request);
        if(userAccount == null){
            return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
        }

    	String id = request.getParameter("id");
        
    	List<StoreAppAccount> storeList = storeAppAccountService.findAccountByStoreInfoId(Integer.parseInt(id));
    	for(StoreAppAccount s : storeList){
    		if(s.getStatus() == 0){
    			return Response.error(MessageCode.REQUEST_ERROR);
    		}
    	}

    	storeManagerService.deleteStoreById(Integer.parseInt(id));
    	
        return Response.success("门店删除成功!");

    }
    
    @RequestMapping(value = "app/account/add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Authentication
    public String listAppAccount(HttpServletRequest request){

        Account userAccount = this.getCommonUserAccount(request);
        if(userAccount == null){
            return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
        }

        int storeId = 0;
        try{
            storeId = Integer.valueOf(request.getParameter("store_info_id"));
        }catch (Exception e){

        }
        if(storeId <= 0){
            return Response.error(MessageCode.NO_DATA,"未知的门店信息");
        }

        StoreInfo storeInfo = storeManagerService.findStoreInfoById(storeId);
        if(storeInfo == null || storeInfo.getCompanyId() != userAccount.getCompanyId()){
            return Response.error(MessageCode.NO_DATA,"你是入侵者么？");
        }

        String userName = StringUtils.trimToEmpty(request.getParameter("user_name"));
        String password = StringUtils.trimToEmpty(request.getParameter("password"));
        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
            return Response.error(MessageCode.NO_DATA, "数据有问题");
        }

        StoreAppAccount storeAppAccount = new StoreAppAccount();
        storeAppAccount.setCompanyId(userAccount.getCompanyId());
        storeAppAccount.setStoreInfoId(storeId);
        storeAppAccount.setUserId(userName);
        storeAppAccount.setPassword(password);
        storeAppAccount.setRoleId(1);
        storeAppAccount.setStatus(1);
        try{
            storeAppAccountService.createAccount(storeAppAccount);
        }catch (Exception e){
            return Response.error(MessageCode.INVALID_OPERATOR, "添加账户失败");
        }

        return Response.success();
    }

    @RequestMapping(value = "app/account/list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Authentication
    public String listStoreAppAccount(HttpServletRequest request){

        String pageNumStr = StringUtils.trimToEmpty(request.getParameter("page_num"));
        String pageSizeStr = StringUtils.trimToEmpty(request.getParameter("page_size"));

        int pageNum = 0;
        int paseCount = 10;

        try{
            pageNum = Integer.valueOf(pageNumStr);
            paseCount = Integer.valueOf(pageSizeStr);
        }catch(Exception e){

        }

        List<StoreAppAccount> accountList = storeAppAccountService.findStoreAppAccountList(pageNum, paseCount, null);

        int hasNextPage = 0;
        if(accountList.size() == (paseCount+1)){
            accountList.remove(paseCount);
            hasNextPage = 1;
        }

        HashMap<String,Object> result = new HashMap<String,Object>();
        result.put("has_more", hasNextPage);
        result.put("store_account_list_list", accountList);
        result.put("current_page", pageNum);

        return Response.success(result);

    }

    /*
     * 门店账户信息列表
     */
    @RequestMapping(value = "app/storeAccount/list/{storeId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Authentication
    public String storeAppAccount(HttpServletRequest request ,@PathVariable("storeId")String storeId){
    	if(!NumberUtils.isDigits(storeId)){
    		return Response.error(MessageCode.PARAMETER_WRONG);
    	}
    	
    	List<StoreAppAccount> accountList = storeAppAccountService.findAccountByStoreInfoId(NumberUtils.toInt(storeId));
    	
    	HashMap<String, Object> datas = new HashMap<>();
    	datas.put("datas", accountList);
    	
    	return Response.success(datas);
    }
    
    /**
	 * @description 创建门店账户 
	 * @version 1.0
	 * @author Scott
	 * @date 2015年12月17日 上午11:48:05
	 * @return String
	 */
	@RequestMapping(value = "/storeAppAccount/create", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	@Authentication
	public String createAppAccount(HttpServletRequest request) {
		try {
			
			String userId = request.getParameter("userId").trim();
			String password = request.getParameter("password").trim();
			int roleId = NumberUtils.toInt(request.getParameter("roleId").trim());
			int storeInfoId = NumberUtils.toInt(request.getParameter("storeInfoId").trim());
			String username = request.getParameter("username").trim();
			StoreAppAccount account = new StoreAppAccount();
			account.setUserId(userId);
			account.setPassword(password);
			account.setStoreInfoId(storeInfoId);
			account.setRoleId(roleId);
			account.setUsername(username);
			
			//创建账户
			accountService.createAccount(account);
			
			return Response.success("创建成功！");
		}  catch (GeneralSecurityException e) {
			e.printStackTrace();
			return Response.error("服务器异常，创建失败");
		}catch (AccountAlreadyExistsException e) {
			e.printStackTrace();
			return Response.error(MessageCode.ACCOUNT_AREADT_EXIT);
		}catch (NullPointerException e) {
			e.printStackTrace();
			return Response.error("参数不完整，请检查输入内容");
		}

	}
	
	/*
	 * 根据公司id查询门店
	 */
	@RequestMapping(value = "/storeAppAccount/storeList", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
	@ResponseBody
	@Authentication
	public String storeList(HttpServletRequest request){
		
		int companyId = this.getCommonUserAccount(request).getCompanyId();
		
		if(companyId <= 0){
			return Response.error(MessageCode.ERROR_NO_LOGIN);
		}
		
		List<HashMap<String, Object>> result = accountService.findStoreByCompany(companyId);
		
		HashMap<String, Object> datas = new HashMap<>();
		datas.put("data", result);
		
		return Response.success(datas);
	}
	
	/*
	 * 激活账户(修改账户状态)
	 */
	@RequestMapping(value = "/storeAppAccount/activate", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	@Authentication
	public String activateAccount(HttpServletRequest request ){
		String userId = request.getParameter("userId").trim();
		if(StringUtils.isEmpty(userId)){
			return Response.error(MessageCode.PARAMETER_WRONG);
		}
		
		accountService.activateAccount(userId);
		
		return Response.success("激活成功，如果忘记密码请联系管理员修改密码");
	}
	
	/*
	 * 修改账户信息
	 */
	@RequestMapping(value = "/storeAppAccount/update", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	@Authentication
	public String updateAccount(HttpServletRequest request){
		
		String id = request.getParameter("id");
		String username = request.getParameter("username").trim();
		String storeId = request.getParameter("storeId").trim();
		String password = request.getParameter("password").trim();
		String status = request.getParameter("status").trim();
				
		
		if(StringUtils.isEmpty(username) || StringUtils.isEmpty(storeId)
				|| StringUtils.isEmpty(status)
				|| !NumberUtils.isDigits(storeId) || !NumberUtils.isDigits(status)
				|| !NumberUtils.isDigits(id)){
			
			return Response.error(MessageCode.PARAMETER_WRONG);
		}
		
		
		
		StoreAppAccount account = new StoreAppAccount();
		account.setId(NumberUtils.toInt(id));
		account.setUsername(username);
		account.setStoreInfoId(NumberUtils.toInt(storeId));
		account.setStatus(NumberUtils.toInt(status));
		if(password.trim().equals("") ||password.trim().length() == 0){
			account.setPassword(null);
		}else{
			account.setPassword(password);
		}
		
		accountService.updateAccount(account);
		
		return Response.success("修改成功");
	}
	
	/*
	 * 删除账户(修改账户状态)
	 */
	@RequestMapping(value = "/storeAppAccount/delete/{id}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
	@ResponseBody
	@Authentication
	public String deleteAppAccount(HttpServletRequest request ,@PathVariable("id")String id){
		if(!NumberUtils.isDigits(id)){
			Response.error(MessageCode.PARAMETER_WRONG);
		}
		accountService.deleteAccount(NumberUtils.toInt(id));
		
		return Response.success("删除成功");
	}
	
	/*
	 * 查询门店所支持的付款类型
	 */
	@RequestMapping(value = "/store_list/payment/{id}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
	@ResponseBody
	@Authentication
	public String getShopPaymentType(HttpServletRequest request ,@PathVariable("id")String id){
		
		if(!NumberUtils.isDigits(id)){
			Response.error(MessageCode.PARAMETER_WRONG);
		}
		
		StoreInfo storeInfo = storeManagerService.findStoreInfoById(NumberUtils.toInt(id));
		if(storeInfo == null){
			return Response.error(MessageCode.NO_DATA,"你是入侵者么？");
		}
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("paymentType", storeInfo.getPaymentType());
		
		return Response.success(map);
	}
	
}









